package org.dk.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.dk.exception.LoginException;
import org.dk.pojo.TbSeller;
import org.dk.service.SellerService;

import java.util.Objects;

public class MyRealm extends AuthorizingRealm {

   @Reference
   private SellerService sellerService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        TbSeller tbSeller = sellerService.selectById(token.getUsername());
        if(tbSeller == null){
            return null;
        }
        if(Objects.equals(tbSeller.getStatus(),"0")){
            throw new LoginException("该帐号正在审核中，请耐心等待");
        }
        if(Objects.equals(tbSeller.getStatus(),"2")){
            throw new LoginException("该帐号审核失败，请联系客服");
        }
        if(Objects.equals(tbSeller.getStatus(),"3")){
            throw new LoginException("该帐号已被关闭，请联系客服");
        }
        //校验密码 交由shiro来帮我们校验   1.登录成功后的对象 2.数据库中的密码 3.数据库中加密的盐 4.用户名称
        return new SimpleAuthenticationInfo(tbSeller,tbSeller.getPassword(),
                ByteSource.Util.bytes(tbSeller.getYan()),tbSeller.getSellerId());

    }
}
